<template>
  <div class="borrow-list">
    <div class="page-header">
      <h2>借阅记录</h2>
      <el-button type="primary" @click="showOverdueConfigDialog">设置超期时间</el-button>
    </div>

    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="书名">
          <el-input v-model="searchForm.bookName" placeholder="请输入书名" clearable />
        </el-form-item>
        <el-form-item label="借阅人">
          <el-input v-model="searchForm.borrower" placeholder="请输入借阅人" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="已借出" value="BORROWED" />
            <el-option label="已归还" value="RETURNED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-table :data="borrowList" border style="width: 100%" v-loading="loading">
      <el-table-column prop="bookName" label="书名" />
      <el-table-column prop="borrower" label="借阅人" />
      <el-table-column prop="contact" label="联系方式" />
      <el-table-column prop="borrowTime" label="借阅时间" />
      <el-table-column prop="returnTime" label="归还时间" />
      <el-table-column prop="remainingDays" label="剩余天数">
        <template #default="{ row }">
          <el-tag :type="getTagType(row.remainingDays)">
            {{ formatRemainingDays(row.remainingDays) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 'BORROWED' ? 'warning' : 'success'">
            {{ row.status === 'BORROWED' ? '已借出' : '已归还' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            v-if="row.status === 'BORROWED'"
            type="success"
            link
            @click="handleReturn(row)"
          >
            归还
          </el-button>
          <el-button
            v-if="row.status !== 'BORROWED'"
            type="primary"
            link
            @click="handleBorrow(row)"
          >
            借出
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="pagination"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :total="total"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 超期时间设置对话框 -->
    <el-dialog
      v-model="overdueConfigDialogVisible"
      title="设置超期时间"
      width="30%"
    >
      <el-form :model="overdueConfigForm" label-width="100px">
        <el-form-item label="超期天数">
          <el-input-number
            v-model="overdueConfigForm.days"
            :min="1"
            :max="365"
            placeholder="请输入超期天数"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="overdueConfigDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveOverdueConfig">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

// 列表数据
const borrowList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  bookName: '',
  borrower: '',
  status: ''
})

// 超期配置相关
const overdueConfigDialogVisible = ref(false)
const overdueConfigForm = reactive({
  days: 30
})

// 获取超期配置
const getOverdueConfig = async () => {
  try {
    const res = await axios.get('/api/overdue-config')
    if (res.data.data) {
      overdueConfigForm.days = res.data.data.days
    }
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('获取超期配置失败')
  }
}

// 显示超期配置对话框
const showOverdueConfigDialog = () => {
  getOverdueConfig()
  overdueConfigDialogVisible.value = true
}

// 保存超期配置
const handleSaveOverdueConfig = async () => {
  try {
    await axios.post('/api/overdue-config', overdueConfigForm.days, {
      headers: {
        'Content-Type': 'application/json'
      },
      transformRequest: [(data) => JSON.stringify(data)]
    })
    ElMessage.success('设置成功')
    overdueConfigDialogVisible.value = false
    getBorrowList()
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('设置失败')
  }
}

// 格式化剩余天数显示
const formatRemainingDays = (days) => {
  if (days === null || days === undefined) return '未知'
  if (days > 0) return `剩余 ${days} 天`
  if (days < 0) return `超期 ${-days} 天`
  return '今日到期'
}

// 获取剩余天数标签类型
const getTagType = (days) => {
  if (days === null || days === undefined) return 'info'
  if (days > 7) return 'success'
  if (days > 0) return 'warning'
  return 'danger'
}

// 获取借阅列表
const getBorrowList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm
    }
    const res = await axios.get('/api/borrows', { params })
    borrowList.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (error) {
    console.error('Error:', error)
    ElMessage.error('获取借阅列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getBorrowList()
}

// 重置
const handleReset = () => {
  searchForm.bookName = ''
  searchForm.borrower = ''
  searchForm.status = ''
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getBorrowList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getBorrowList()
}

// 借出图书
const handleBorrow = async (row) => {
  try {
    await ElMessageBox.confirm('确定要借出这本书吗？', '提示', {
      type: 'warning'
    })
    await axios.post(`/api/borrows/${row.id}/borrow`)
    ElMessage.success('借出成功')
    getBorrowList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error:', error)
      ElMessage.error('借出失败')
    }
  }
}

// 归还图书
const handleReturn = async (row) => {
  try {
    await ElMessageBox.confirm('确定要归还这本书吗？', '提示', {
      type: 'warning'
    })
    await axios.post(`/api/borrows/${row.id}/return`)
    ElMessage.success('归还成功')
    getBorrowList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error:', error)
      ElMessage.error('归还失败')
    }
  }
}

onMounted(() => {
  getBorrowList()
  getOverdueConfig()
})
</script>

<style scoped>
.borrow-list {
  min-height: 100%;
}

.page-header {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
